package com.atjg.autocat.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * @param interval 单位毫秒，用于定时器延迟时间开启，例如：interval = 5000，则是5秒后才会开始倒计时
 * @param duration 单位毫秒，用户每次定时任务间隔时长执行1次，例如 duration = 1000，则每间隔1秒执行1次
 * @param totalTime 单位毫秒,用于定时器执行的总时长，
 *        如果为空的话，会一直在运行，直到手动调用cancel 方法，或者所在协程声明周期结束 而结束
 * @onNext(count) ,返回每次执行的次数
 * @onFinish() 任务正常执行完成
 */
fun CoroutineScope.startTime(
    totalTime: Long? = null,
    onNext: (Long) -> Unit,
    onFinish: (() -> Unit)? = null,
    interval: Long? = 0,
    duration: (Long)  = 1000,
): Job {
    if (duration <= 0) {
        throw IllegalArgumentException("间隔时间必须大于0")
    }
    return this.launch {
        interval?.let { _interval ->
            if (_interval > 0) {
                delay(_interval)
            }
        }

        var isStart = true
        var runAllTotalTime: Long = 0
        var count = (totalTime?:1000) / 1000
        while (isStart) {
            if (totalTime != null && totalTime > 0 && runAllTotalTime >= totalTime) {
                isStart = false
                onFinish?.invoke()
            } else {
                delay(duration)
                runAllTotalTime += duration
                count--
                onNext.invoke(count)
            }
        }
    }
}


fun CoroutineScope.start(
    onNext: (Long) -> Unit,
    duration: (Long)  = 1000,
): Job {
    if (duration <= 0) {
        throw IllegalArgumentException("间隔时间必须大于0")
    }
    return this.launch {
        var isStart = true
        var count = 0L
        while (isStart) {
            delay(duration)
            count++
            onNext.invoke(count)
        }
    }
}